﻿@typeparam TItem
@inject NavigationManager NavigationManager

@if (Data is not null)
{
    <AntList DataSource="Data.Results" Header="@Header">
        <ChildContent Context="item">
            @ItemTemplate(item)
        </ChildContent>
        
    </AntList>

    @if (Data.CurrentPage is not null)
    {
        <div class="text-center m-1">
            <AntDesign.Pagination Total="Data.CurrentPage.TotalCount" Current="Data.CurrentPage.CurrentPage + 1"
                                  PageSize="Data.CurrentPage.PageSize"
                                  CurrentChanged="onPageTo" HideOnSinglePage
                                  ItemRender="PaginationItemRenderer" ShowSizeChanger="@false"></AntDesign.Pagination>
        </div>
    }
}

@code {
    // If null or empty, no page navigation support
    [Parameter]
    public string PageNavigationUrl { get; set; } = "";

    [Parameter]
    public PagingData<TItem> Data { get; set; }

    [Parameter]
    public int? Column { get; set; } = null;

    [Parameter]
    public RenderFragment<TItem> ItemTemplate { get; set; }

    [Parameter]
    public RenderFragment Header { get; set; }

    [Parameter]
    public EventCallback OnUpdatePage { get; set; }

    [Parameter]
    public EventCallback<int> OnPageTo { get; set; }

    RenderFragment<PaginationItemRenderContext> PaginationItemRenderer = ctx => ctx.DefaultRender(ctx);

    private async Task onPageTo(int pageNumber)
    {
        if (string.IsNullOrEmpty(PageNavigationUrl))
        {
            await OnPageTo.InvokeAsync(pageNumber - 1);
        }
    }

    protected override void OnParametersSet()
    {
        if (string.IsNullOrEmpty(PageNavigationUrl))
        {
            PaginationItemRenderer = ctx => 
            @<Template>
                @ctx.DefaultRender(ctx)
            </Template>;
        }
        else
        {
        PaginationItemRenderer = ctx => @<Template>
            @if (ctx.Type is "page")
            {
                <a href="@($"{PageNavigationUrl}/pages/{ctx.Page - 1}")">
                    @ctx.DefaultRender(ctx)
                </a>
            }
            else if (ctx.Type is "prev" && Data.CurrentPage.HasPreviousPage)
            {
                <a href="@($"{PageNavigationUrl}/pages/{Data.CurrentPage.CurrentPage - 1}")">
                    @ctx.DefaultRender(ctx)
                </a>
            }
            else if (ctx.Type is "next" && Data.CurrentPage.HasNextPage)
            {
                <a href="@($"{PageNavigationUrl}/pages/{Data.CurrentPage.CurrentPage + 1}")">
                    @ctx.DefaultRender(ctx)
                </a>
            }
            else
            {
                @ctx.DefaultRender(ctx)
            }
        </Template>;
        }
        base.OnParametersSet();
    }
}
